package com.atxwq.shop.common.log.aspect;

import com.atxwq.shop.common.log.annotation.Log;
import com.atxwq.shop.common.log.service.AsyncOperLogService;
import com.atxwq.shop.common.log.utils.LogUtil;
import com.atxwq.shop.model.entity.system.SysOperLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description 切面类
 * @Date 2025/5/16 22:22
 * @Created by 12336
 */

@Aspect
@Component
@Slf4j
public class LogAspect {

    @Autowired
    private AsyncOperLogService asyncOperLogService ;

    public LogAspect(AsyncOperLogService asyncOperLogService) {
        this.asyncOperLogService = asyncOperLogService;
    }

    @Around(value = "@annotation(sysLog)")
    public Object doAroundAdvice(ProceedingJoinPoint joinPoint, Log sysLog){

//        String title = sysLog.title();
//        log.info("LogAspect...doAroundAdvice方法执行了"+title);
//
//        int businessType = sysLog.businessType();
//        System.out.println("title"+title+"::businessType:" + businessType);
        //封装数据
        SysOperLog sysOperLog = new SysOperLog();
        LogUtil.beforeHandleLog(sysLog, joinPoint, sysOperLog);
        //业务方法
        Object proceed = null;
        try {
            proceed = joinPoint.proceed();
            //调用业务方法之后封装数据
            LogUtil.afterHandlLog(sysLog, proceed, sysOperLog, 0, null);
        } catch (Throwable e) {
            //业务方法执行异常打印
            e.printStackTrace();
            LogUtil.afterHandlLog(sysLog, proceed, sysOperLog, 1, e.getMessage());
            throw new RuntimeException(e);
        }
        //调用service层保存日志
        asyncOperLogService.saveSysOperLog(sysOperLog);

        return proceed;
    }
}
